<script lang="tsx">
import { defineComponent, ref, reactive, onMounted, watch } from 'vue';
import { $t } from '#/locales';
import { ElPagination } from 'element-plus';
import TreeSelector from './modules/tree-selector.vue';
import CourseCard from './modules/course-card.vue';
import { getSubjectCategoryTreeListsApi, getPublicCourseInfoListApi, type CourseInfo } from '#/api/course';
import { courseClickTrackingApi } from '#/api/manage/course';
import { trimStringParams } from '#/utils/trimStringParams';
import corseBanner from '#/assets/images/corse-banner.png';
import { useGlobalSearch } from '#/views/home/hooks/useGlobalSearch';
import { useRouter } from 'vue-router';
import RankingCard from './modules/ranking-card.vue';

export default defineComponent({
  name: 'Course',
  setup() {
    const router = useRouter();
    const activeCategory = ref('');
    const activeCategoryName = ref($t('course.allCategories'));
    const loading = ref(false);

    // 课程数据
    const courseList = ref<CourseInfo[]>([]);
    const queryData = reactive({
      keyWord: '',
      subjectCategoryId: '',
      courseSortType: 'newest'
    });
    const pageInfo = reactive({
      curPage: 1,
      pageSize: 20,
      total: 1
    });

    // 榜单推荐数据
    const hotCourseList = ref<CourseInfo[]>([]);
    const newCourseList = ref<CourseInfo[]>([]);
    const { onSearch } = useGlobalSearch();

    // 获取课程列表数据（接口调用）
    const fetchCourseList = async () => {
      try {
        loading.value = true;
        const params = {
          curPage: pageInfo.curPage,
          pageSize: pageInfo.pageSize,
        } as any
        const trimData = trimStringParams(queryData)
        console.log(trimData)
        Object.keys(trimData).forEach(key => {
          const kVal = trimData[key as keyof typeof trimData]
          if (kVal) {
            params[key] = kVal
          }
        })
        const res = await getPublicCourseInfoListApi(params);
        courseList.value = Array.isArray(res?.data) ? res.data : [];
        pageInfo.total = res?.pageInfo?.totalRows ?? 0;
      } catch (error) {
        console.error('Failed to fetch course list:', error);
        courseList.value = [];
        pageInfo.total = 0;
      } finally {
        loading.value = false;
      }
    };

    // 监听全局搜索事件：更新关键字并重新拉取列表
    onSearch((keyword: string) => {
      queryData.keyWord = keyword || '';
      pageInfo.curPage = 1;
      fetchCourseList();
    });

    // 获取榜单推荐数据
    const fetchRankingData = async () => {
      try {
        // 获取最热门课程
        const hotParams = {
          curPage: 1,
          pageSize: 3,
          courseSortType: 'hottest'
        };
        const hotRes = await getPublicCourseInfoListApi(hotParams);
        hotCourseList.value = Array.isArray(hotRes?.data) ? hotRes.data : [];

        // 获取最新课程
        const newParams = {
          curPage: 1,
          pageSize: 3,
          courseSortType: 'newest'
        };
        const newRes = await getPublicCourseInfoListApi(newParams);
        newCourseList.value = Array.isArray(newRes?.data) ? newRes.data : [];
      } catch (error) {
        console.error('Failed to fetch ranking data:', error);
        hotCourseList.value = [];
        newCourseList.value = [];
      }
    };

    // 处理分类切换
    const handleCategoryChange = (categoryId: string, categoryName: string) => {
      activeCategory.value = categoryId;
      activeCategoryName.value = categoryName;
      queryData.subjectCategoryId = categoryId;
      // 重置分页并重新获取课程数据
      pageInfo.curPage = 1;
      fetchCourseList();
    };

    // 处理排序切换
    const handleSortChange = (type: 'newest' | 'hottest') => {
      if (queryData.courseSortType === type) return;
      queryData.courseSortType = type;
      // 重置分页并重新获取课程数据
      pageInfo.curPage = 1;
      fetchCourseList();
    };

    // 处理分页器页码变化
    const handlePageChange = (page: number) => {
      pageInfo.curPage = page;
      fetchCourseList();
    };

    // 处理分页器每页大小变化
    const handleSizeChange = (size: number) => {
      pageInfo.pageSize = size;
      pageInfo.curPage = 1;
      fetchCourseList();
    };

    // 自定义跳页输入与跳转
    const jumperInput = ref<string>('');
    // 同步输入框与当前页
    watch(
      () => pageInfo.curPage,
      (n) => {
        jumperInput.value = String(n ?? 1);
      },
      { immediate: true }
    );
    const goToPage = () => {
      const totalPages = Math.max(1, Math.ceil(pageInfo.total / pageInfo.pageSize));
      const n = Number(jumperInput.value);
      if (!n || isNaN(n)) return;
      const target = Math.min(totalPages, Math.max(1, Math.floor(n)));
      if (target !== pageInfo.curPage) {
        handlePageChange(target);
      }
    };

    // 组件挂载时获取数据
    onMounted(() => {
      fetchCourseList();
      fetchRankingData();
    });

    // 处理课程卡片点击事件
    const handleCourseClick = async (course: CourseInfo) => {
      // 课程点击埋点
      try {
        await courseClickTrackingApi(course.id);
      } catch (error) {
        console.error('课程点击埋点失败:', error);
      }
      // 这里可以添加跳转到课程详情页的逻辑
      router.push(`/lesson/intro?courseId=${course.id}`);
    };

    return () => (
      <div class="course-page bg-[#EDEEF5]">
        {/* 横幅区域 */}
        <div class="w-full">
          <img
            src={corseBanner}
            alt={$t('course.courseBanner')}
            class="w-full h-auto object-cover"
          />
        </div>

        {/* 分类选择区域 */}
        <div class="max-w-[1200px] mx-auto mt-[15px] mb-[32px]">
          <TreeSelector
            v-model:modelValue={activeCategory.value}
            fetchData={getSubjectCategoryTreeListsApi}
            onChange={handleCategoryChange}
            allText={$t('course.allCategories')}
          />
        </div>

        {/* 主要内容区域 */}
        <div class="max-w-[1200px] mx-auto">
          {/* 课程列表 */}
          <div>
            <div class="flex items-center mb-[16px]">
              <h2 class="text-[24px] leading-[32px] font-[500] text-[#191919]">{activeCategoryName.value}</h2>
            </div>

            <div class="flex items-center gap-[24px] mb-[12px] text-[#595959]">
              <span class={`text-[14px] leading-[22px] cursor-pointer hover:text-[#0067D1] ${queryData.courseSortType === 'newest' ? 'text-[#0067D1]' : ''}`} onClick={() => handleSortChange('newest')}>{$t('course.newest')}</span>
              <span class={`text-[14px] leading-[22px] cursor-pointer hover:text-[#0067D1] ${queryData.courseSortType === 'hottest' ? 'text-[#0067D1]' : ''}`} onClick={() => handleSortChange('hottest')}>{$t('course.hottest')}</span>
            </div>

            {loading.value ? (
              <div class="flex justify-center items-center py-12">
                <div class="text-gray-500">{$t('course.loading')}</div>
              </div>
            ) : courseList.value.length > 0 ? (
              <>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-[24px] mb-8">
                  {courseList.value.map((course) => (
                    <CourseCard
                      key={course.id}
                      course={course}
                      cardType="course"
                      showPlayButton={true}
                      showTag={true}
                      onClick={handleCourseClick}
                    />
                  ))}
                </div>

                {/* 分页器 */}
                <div class="flex justify-center">
                  <ElPagination
                    v-model:current-page={pageInfo.curPage}
                    v-model:page-size={pageInfo.pageSize}
                    layout="prev, pager, next, ->, slot"
                    total={pageInfo.total}
                    background
                    onCurrent-change={handlePageChange}
                    onSize-change={handleSizeChange}
                  >
                    {{
                      default: () => (
                        <div class="flex items-center gap-2 ml-3 text-[#8C8C8C]">
                          <span>{$t('course.jumpTo')}</span>
                          <input
                            value={jumperInput.value}
                            onInput={(e) => (jumperInput.value = (e.target as HTMLInputElement).value)}
                            onKeydown={(e) => { if ((e as KeyboardEvent).key === 'Enter') goToPage(); }}
                            class="w-[40px] h-[40px] rounded-[16px] border border-[#E5E6EB] text-center outline-none"
                          />
                          <span>{$t('course.page')}</span>
                          <span
                            class="text-[#595959] text-[14px] leading-[38px] rounded-[16px] w-[40px] h-[40px] bg-[#fff] text-center cursor-pointer hover:bg-[#E5E6EB]"
                            onClick={goToPage}
                          >
                            {$t('course.go')}
                          </span>
                        </div>
                      )
                    }}
                  </ElPagination>
                </div>
              </>
            ) : (
              <div class="flex justify-center items-center py-12">
                <div class="text-gray-500">{$t('course.noCourseData')}</div>
              </div>
            )}
          </div>
        </div>

        {/* 榜单推荐区域 */}
        <div class="pt-[32px] mt-[31px] pb-[32px] w-full bg-white">
          <div class="max-w-7xl mx-auto">
            <h2 class="text-2xl font-bold text-gray-800 mb-6">{$t('course.courseRankingRecommendation')}</h2>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
              <RankingCard
                title={$t('course.hottest')}
                variant="hot"
                list={hotCourseList.value}
                onItemClick={handleCourseClick}
              />
              <RankingCard
                title={$t('course.newest')}
                variant="new"
                list={newCourseList.value}
                onItemClick={handleCourseClick}
              />
            </div>
          </div>
        </div>

      </div>
    );
  },
});
</script>

<style lang="less" scoped>
.course-page {
  // 课程页面样式
}

.el-pagination {
  :deep(.btn-prev) {
    border-radius: 16px;
    height: 40px;
    line-height: 40px;
    min-width: 40px;
  }

  :deep(.btn-next) {
    border-radius: 16px;
    height: 40px;
    line-height: 40px;
    min-width: 40px;
  }

  :deep(.el-pager) {
    background-color: #fff;
    border-radius: 16px;

    li {
      border-radius: 16px;
      height: 36px;
      line-height: 36px;
      min-width: 36px;
      background-color: #fff;
    }
  }
}
</style>
